﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
using System.Xml;

namespace ProjetIntegrationMobilite
{
    public partial class Form1 : Form
    {
        #region statement
        public bool tabOk = false;
        public bool white_black;
        public List<User> listUser = new List<User>();
        public List<Board> listBoard = new List<Board>();
        #endregion

        #region builder
        public Form1()
        {
            InitializeComponent();
            ChargementDonnée();
        }
        #endregion

        public void ChargementDonnée()
        {
            try
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(List<Board>));
                TextReader textReader = new StreamReader(Directory.GetCurrentDirectory() + @"\saveBoard.xml");
                listBoard = (List<Board>)deserializer.Deserialize(textReader);
                textReader.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            for (int i = 0; i < listBoard.Count; i++)
            {
                listBox2.Items.Add(listBoard[i].Name);
            }

            try
            {
                XmlSerializer deserializer2 = new XmlSerializer(typeof(List<User>));
                TextReader textReader2 = new StreamReader(Directory.GetCurrentDirectory() + @"\saveUser.xml");
                listUser = (List<User>)deserializer2.Deserialize(textReader2);
                textReader2.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            for (int i = 0; i < listUser.Count; i++)
            {
                listBox1.Items.Add(listUser[i].name);
            }
        }

        #region Resource: User
        public int CreerUser(string nom, string pseudo, string password)
        {
            User testUser = new User(nom, pseudo, password);

            #region Empty list
            if (listUser.Count == 0)
            {
                listUser.Add(testUser);
                listBox1.Items.Add(testUser.name);
                try
                {
                    XmlSerializer serializerUser = new XmlSerializer(typeof(List<User>));
                    TextWriter textWriterUser = new StreamWriter(Directory.GetCurrentDirectory() + @"\saveUser.xml");
                    serializerUser.Serialize(textWriterUser, listUser);
                    textWriterUser.Close();
                    return 1;
                }
                catch (Exception)
                {
                    return 0;
                }
            }
            #endregion
            else
            {
                for (int i = 0; i < listUser.Count; i++)
                {
                    if (pseudo == listUser[i].name)
                    {
                        return 0;
                    }
                }
                    
                listUser.Add(testUser);
                listBox1.Items.Add(testUser.name);
                try
                {
                    XmlSerializer serializerUser = new XmlSerializer(typeof(List<User>));
                    TextWriter textWriterUser = new StreamWriter(Directory.GetCurrentDirectory() + @"\SaveUser.xml");
                    serializerUser.Serialize(textWriterUser, listUser);
                    textWriterUser.Close();
                    return 1;
                }
                catch (Exception)
                {
                }
                return 2;
            }
        }

        public int ListerUser()
        {
            try
            {
                String XmlizedString = null;
                UserListResponse pObjectUser = new UserListResponse();
                XmlRootAttribute xRoot = new XmlRootAttribute("goimerir");
                for (int i = 0; i < listUser.Count; i++)
                {
                    pObjectUser.user.Add(new UserListResponse.CompactUserModel(listUser[i]));
                }
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(typeof(UserListResponse), xRoot);
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                xs.Serialize(xmlTextWriter, pObjectUser);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                System.IO.File.WriteAllText(Directory.GetCurrentDirectory() + @"\ListUser.xml", XmlizedString);
                return 1;
            }
            catch (Exception)
            {
                return 0;
            }
           
        }

        #endregion

        #region Resource: Board
        public int CreerBoard(string pseudoUser1, string pseudoUser2, string nameBoard, string size, bool color)
        {
            if (size == "")
            {
                size = "9x9";
            }

            Board testBoard = new Board(pseudoUser1, pseudoUser2,nameBoard,size, DateTime.Now, color);

            if (pseudoUser2 == "")
            {
                testBoard.status = "OPEN";
            }
            else
            {
                testBoard.status = "FULL";
            }

            listBoard.Add(testBoard);
            listBox2.Items.Add(testBoard.Name);
            try
            {
                XmlSerializer serializerBoard = new XmlSerializer(typeof(List<Board>));
                TextWriter textWriterBoard = new StreamWriter(Directory.GetCurrentDirectory() + @"\SaveBoard.xml");
                serializerBoard.Serialize(textWriterBoard, listBoard);
                textWriterBoard.Close();
                return 1;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public int EffacerBoard(string nameBoard)
        {
            for (int i = 0; i < listBoard.Count; i++)
            {
                if (listBoard[i].Name == nameBoard)
                {
                    listBoard.Remove(listBoard[i]);
                    listBox2.Items.Remove(listBoard[i].Name);
                    return 1;
                }
            }
            return 0;
        }

        public int ListerBoard()
        {
            try
            {
                String XmlizedString = null;
                BoardsListResponse pObjectBoard = new BoardsListResponse();
                XmlRootAttribute xRoot = new XmlRootAttribute("goimerir");
                for (int i = 0; i < listBoard.Count; i++)
                {
                    pObjectBoard.listBoards.Add(new BoardsListResponse.CompactBoardListModel(listBoard[i]));
                }
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(typeof(BoardsListResponse), xRoot);
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                xs.Serialize(xmlTextWriter, pObjectBoard);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                System.IO.File.WriteAllText(Directory.GetCurrentDirectory() + @"\ListBoard.xml", XmlizedString);
                return 1;
            }
            catch (Exception)
            {
                return 0;
            }
        }
        #endregion

        #region Game
        public int InviteUserJoinBoard(string user, string invite)
        {
            for (int i = 0; i < listBoard.Count; i++)
            {
                if (listBoard[i].owner == user && listBoard[i].status == "OPEN")
                {
                    listBoard[i].invite = invite;
                    listBoard[i].status = "FULL";
                    return 1;
                }
            }
            return 0;
        }

        public int PermissionToJoin(string j1)
        {
            for (int i = 0; i < listBoard.Count; i++)
            {
                if (listBoard[i].owner == j1)
                {
                    if (listBoard[i].status == "OPEN")
                    {
                        return 1;
                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return 0;
                }
            }
            return 0;
        }

        public int MovePlay(int row, int column,string board)
        {
            for (int i = 0; i < listBoard.Count; i++)
            {
                if (listBoard[i].Name == board && listBoard[i].status !="CLOSE")
                {
                    #region Test if the board has to be closed
                    if ((listBoard[i - 1].listMove.Last().Column == null && listBoard[i - 1].listMove.Last().Row == null) && (row == null && column == null))
                    {
                        listBoard[i].status = "CLOSE";
                        listBoard[i].listMove.Add(new Moves(row, column));
                        return listBoard[i].PostionPoints(row, column);
                    }
                    #endregion
                    else
                    {
                        listBoard[i].listMove.Add(new Moves(row, column));
                        return listBoard[i].PostionPoints(row, column);
                    }
                }
            }
            return 0;
        }

        #region Retrieve a board to play
        public int listHistoryMove(string board)
        {
            //try
            //{
                String XmlizedString = null;
                BoardResponse pObjectBoard = new BoardResponse();
                XmlRootAttribute xRoot = new XmlRootAttribute("goimerir");
                for (int i = 0; i < listUser.Count; i++)
                {
                    if (listBoard[i].Name == board)
                    {
                        pObjectBoard.boards.Add(new BoardResponse.CompactBoardModel(listBoard[i]));
                    }
                }
                MemoryStream memoryStream = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(typeof(BoardResponse), xRoot);
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

                xs.Serialize(xmlTextWriter, pObjectBoard);
                memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
                System.IO.File.WriteAllText(Directory.GetCurrentDirectory() + @"\Board.xml", XmlizedString);
                return 1;
            //}
            //catch (Exception)
            //{
            //    return 0;
            //}
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            int i = CreerBoard("toto","","testA","",true);
            int j = CreerBoard("toto", "truc", "toi", "16x16", true);
            int k = CreerBoard("toto", "titoc", "lui", "9x9", true);

            int q = CreerUser("ludovic", "ptiludo", "azerty");
            int w = CreerUser("ben", "ptiludo", "azerty");
            int s = CreerUser("pierre", "pierro", "sty");
            int t = CreerUser("alian", "alinA", "wxcde");
            ListerBoard();
            ListerUser();
            int u = listHistoryMove("toi");
        }

        #endregion

        private static String UTF8ByteArrayToString(Byte[] characters)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            String constructedString = encoding.GetString(characters);
            return (constructedString);
        }
    }
}
